import { Injectable, OnModuleInit, OnModuleDestroy, Logger } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class DatabaseService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
  private readonly logger = new Logger(DatabaseService.name);

  async onModuleInit() {
    try {
      await this.$connect();
      this.logger.log('Database connected successfully');
    } catch (error) {
      this.logger.error('Failed to connect to database:', error);
      throw error;
    }
  }

  async onModuleDestroy() {
    await this.$disconnect();
    this.logger.log('Database disconnected');
  }

  async healthCheck(): Promise<boolean> {
    try {
      await this.$queryRaw`SELECT 1`;
      return true;
    } catch (error) {
      this.logger.error('Database health check failed:', error);
      return false;
    }
  }

  /**
   * 执行原始SQL查询
   */
  async query(sql: string, params?: any[]): Promise<any> {
    try {
      // 使用Prisma的$queryRawUnsafe来执行原始SQL查询
      const result = await this.$queryRawUnsafe(sql, ...(params || []));
      
      // 如果是SELECT查询，返回结果；否则返回行数
      if (Array.isArray(result)) {
        return { rows: result };
      } else {
        return { rows: [], count: result };
      }
    } catch (error) {
      this.logger.error('Query execution failed:', error);
      throw error;
    }
  }
}
